<template>
    <el-dialog :title="title" v-model="dialogVisible" width="1000px" destroy-on-close append-to-body
        style="padding-bottom: 20px;">
        <div class="dict-items-container">
            <!-- 操作按钮 -->
            <div class="header">
                <el-button v-permissions="{
                    permission: ['system:dictItem:doAdd']
                }" type="primary" @click="handleAdd" :icon="Plus">新增</el-button>
                <el-form :inline="true" :model="queryParams">
                    <el-form-item style="margin-right: 10px !important;">
                        <el-input v-model="queryParams.name" placeholder="请输入字典项名称" clearable
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item style="margin-right: 10px !important;">
                        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                            <el-option label="启用" :value="1" />
                            <el-option label="禁用" :value="0" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 表格 -->
            <el-table v-loading="loading" :data="itemList" border row-key="item_id">
                <el-table-column type="expand">
                    <template #default="{ row }">
                        <el-table :data="row.langs" border>
                            <el-table-column width="50">
                                <template #default="{ row: lang }">
                                    <el-image :src="lang.language?.icon" style="width: 20px; height: 20px;"
                                        :preview-src-list="[]" />
                                </template>
                            </el-table-column>
                            <el-table-column label="语言" prop="language.name" width="120" />
                            <el-table-column label="名称" prop="name" min-width="120" />
                            <el-table-column label="备注" prop="remark" min-width="200" />
                            <el-table-column label="语言代码" prop="language.code" width="120" align="center" />
                            <el-table-column label="默认" width="80" align="center">
                                <template #default="{ row: lang }">
                                    <el-tag v-if="lang.language?.is_default" type="success" size="small">是</el-tag>
                                    <el-tag v-else type="info" size="small">否</el-tag>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-table-column>

                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="value" label="字典值" min-width="120" align="center" show-overflow-tooltip />
                <el-table-column prop="name" label="字典项名称" min-width="120" align="center" show-overflow-tooltip />
                <el-table-column prop="remark" label="备注说明" min-width="120" align="center" show-overflow-tooltip />
                <el-table-column prop="sort" label="排序" width="80" align="center" />
                <el-table-column label="状态" width="80" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                            {{ row.status === 1 ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="create_time" label="创建时间" min-width="160" align="center" show-overflow-tooltip />
                <el-table-column label="操作" width="180" align="center" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleEdit(row)" v-permissions="{
                            permission: ['system:dictItem:doEdit']
                        }">编辑</el-button>
                        <el-button type="danger" link @click="handleDelete(row)" v-permissions="{
                            permission: ['system:dictItem:doDelete']
                        }">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 字典项表单组件 -->
        <dict-item-form v-model:visible="formVisible" :type="formType" :dict-id="dictId" :current-row="currentRow"
            @success="getList" />
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getDictItemList, deleteDictItem } from '/@/api/dict'
import type { DictItem, DictItemQuery } from '/@/types/dict'
import type { Language as LanguageType } from '/@/types/language'
import { useUserStore } from '/@/store/modules/user'
import DictItemForm from './DictItemForm.vue'

const props = defineProps<{
    visible: boolean
    dictId: number
}>()

const emit = defineEmits(['update:visible'])

const dialogVisible = computed({
    get: () => props.visible,
    set: (val) => emit('update:visible', val)
})

const title = computed(() => '字典项管理')
const loading = ref(false)
const itemList = ref<DictItem[]>([])
const formVisible = ref(false)
const formType = ref<'add' | 'edit'>('add')
const currentRow = ref<DictItem | null>(null)

// 查询参数
const queryParams = reactive<DictItemQuery>({
    dict_id: props.dictId,
})

// 获取列表数据
const getList = async () => {
    if (!dialogVisible.value) return // 如果弹窗未显示，不请求数据
    
    loading.value = true
    try {
        const { data } = await getDictItemList(queryParams)
        itemList.value = data.list
    } finally {
        loading.value = false
    }
}

// 查询操作
const handleQuery = () => {
    getList()
}

// 重置操作
const resetQuery = () => {
    queryParams.name = undefined
    queryParams.status = undefined
    handleQuery()
}

// 新增操作
const handleAdd = () => {
    formType.value = 'add'
    currentRow.value = null
    formVisible.value = true
}

// 编辑操作
const handleEdit = (row: DictItem) => {
    formType.value = 'edit'
    currentRow.value = row
    formVisible.value = true
}

// 删除操作
const handleDelete = async (row: DictItem) => {
    try {
        await ElMessageBox.confirm(
            `确认要删除"${row.name}"吗？删除后将无法恢复！`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        await deleteDictItem(row.item_id)
        ElMessage.success('删除成功')
        getList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
        }
    }
}

// 监听 dictId 和弹窗显示状态变化
watch([() => props.dictId, () => dialogVisible.value], ([dictId, visible]) => {
    queryParams.dict_id = dictId
    if (visible) {
        getList() // 弹窗显示时获取数据
    } else {
        // 弹窗关闭时清空数据
        itemList.value = []
        queryParams.name = undefined
        queryParams.status = undefined
    }
})
</script>

<style lang="scss" scoped>
.dict-items-container {
    .header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16px;
    }
}

:deep(.el-space) {
    justify-content: center;
}

:deep(.el-tag) {
    cursor: default;
}

:deep(.el-table__expanded-cell) {
    padding: 20px !important;
}

:deep(.el-table__expand-icon) {
    .el-icon {
        font-size: 12px;
    }
}

:deep(.el-image) {
    display: block;
    border-radius: 2px;
    overflow: hidden;
}
</style>